import Taro, { Component } from '@tarojs/taro'
import NetWork from '../../util/network'
import './index.scss'
export default class questionnaire extends Component {
  state = {
    code: '',
    phone: "",
    isSend: false,
    second: 60
  }
  config = {
    navigationBarTitleText: '绑定手机号码'
  }
  changeVal(name, e) {
    switch (name) {
      case 'code':
        this.setState({
          code: Number(e.target.value)
        })
        break;
      case 'phone':
        this.setState({
          phone: e.target.value
        })
        break;
    }
  }
  async subMitVal() {
    let res = await NetWork({
      url: "/api/createmember",
      method: "post",
      data: {
        phone: this.state.phone,
        msgCode: this.state.code,
        thirdPlatformInfoDTO: {
          wechatopenid: this.$router.params.thirdPlatformInfoDTO
        }
      }
    })
    if (!res) {
      return false
    }
    Taro.setStorage({
      key:"Authorization",
      data:res
    })
    Taro.redirectTo({
      url: '/pages/index/index'
    })
  }
  async getYZM() {
    let { isSend, phone } = this.state
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
      Taro.showToast({
        title: "手机号码不正确",
        duration: 2000,
        mask: false,
        icon: "none"
      })
      return false;
    }
    if (isSend) {
      return false
    }
    let result = await NetWork({
      url: "/api/msgCode/getMsgCode",
      data: {
        phone: phone
      },
      method: 'get'
    })
    this.setState({
      isSend: true
    })
    let that = this
    let clear = setInterval(() => {
      that.setState({
        second: that.state.second - 1
      })
      if (that.state.second <= 1) {
        clearInterval(clear)
        that.setState({
          isSend: false
        })
      }
    }, 1000);
    Taro.showToast({
      title: "发送成功",
      duration: 2000,
      mask: false,
      icon: "none"
    })

  }
  render() {
    return (
      <View className='formwarp'>
        <View className='item'>
          <Text>手机号</Text>
          <Input type='text' value={this.state.phone} onInput={this.changeVal.bind(this, 'phone')} />
        </View>
        <View className='item yzm'>
          <Text>验证码</Text>
          <Input type='text' value={this.state.code} onInput={this.changeVal.bind(this, 'code')} />
          <Button class="mini-btn" size="mini"
            onClick={this.getYZM.bind(this)}>{!this.state.isSend ? '获取验证码' : this.state.second + 's后'}</Button>
        </View>
        <Button className='submit' size='mini' onClick={this.subMitVal.bind(this)}>提 交</Button>
      </View>)
  }
}